﻿namespace EFS.Common.UI.Controls
{
	public static class DefaultButtonService
	{
		public static readonly System.Windows.DependencyProperty DefaultButtonProperty =
			System.Windows.DependencyProperty.RegisterAttached("DefaultButton", typeof(System.String), typeof(DefaultButtonService), new System.Windows.PropertyMetadata(OnDefaultButtonChanged));


		/// GetDefaultButton
		public static System.String GetDefaultButton(System.Windows.DependencyObject d)
		{
			return (System.String)d.GetValue(DefaultButtonProperty);
		}

		/// <summary>
		/// Sets the CommandParameter property.
		/// </summary>
		public static void SetDefaultButton(System.Windows.DependencyObject d, System.String value)
		{
			d.SetValue(DefaultButtonProperty, value);
		}

		private static void OnDefaultButtonChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)
		{
			System.Windows.UIElement uiElement = d as System.Windows.UIElement;
			if (uiElement != null)
			{
				uiElement.KeyUp += new System.Windows.Input.KeyEventHandler(uiElement_KeyUp);
			}
		}

		// tb_KeyUp
		private static void uiElement_KeyUp(System.Object sender, System.Windows.Input.KeyEventArgs e)
		{
			switch (e.Key)
			{
				case System.Windows.Input.Key.Enter:
					{
						System.Windows.FrameworkElement frmElement = sender as System.Windows.FrameworkElement;
						if (null == frmElement)
						{
							break;
						}

						// get parent
						System.Windows.FrameworkElement frmElementParent = frmElement.Parent as System.Windows.FrameworkElement;
						if (null == frmElementParent)
						{
							break;
						}

						// button name
						System.String nameButton = (System.String)((System.Windows.DependencyObject)sender).GetValue(DefaultButtonProperty);
						if (!EFS.Common.Verify.String(nameButton))
						{
							break;
						}

						// get button
						System.Windows.Controls.Button button = frmElementParent.FindName(nameButton) as System.Windows.Controls.Button;
						if (null == button && !button.IsEnabled)
						{
							break;
						}

						// get automation
						System.Windows.Automation.Peers.ButtonAutomationPeer peer = new System.Windows.Automation.Peers.ButtonAutomationPeer(button);

						// invoke
						System.Windows.Automation.Provider.IInvokeProvider ip = (System.Windows.Automation.Provider.IInvokeProvider)peer;
						ip.Invoke();

						// ok
						break;
					}
				default:
					{
						break;
					}
			}
		}
	}

}